package gormv2

import (
	"fmt"
	"gitee.com/youbeiwuhuan/gin-practice/go-dbsharding/example/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"
)

func initDb() *gorm.DB {
	dsn := "root:fan1988@tcp(127.0.0.1:3306)/gdbc?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		//Logger: logger.Default.LogMode(logger.Info), //配置日志级别，打印出所有的sql
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: "t_", // 表名前缀，`User` 的表名应该是 `t_users`
		},
	})
	if err != nil {
		fmt.Println("open mysql failed,", err)
		panic(err)
	}

	// 注册插件
	//db.Use()
	//db.Use(crypto.NewCryptoPlugin())

	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(500)
	sqlDB.SetConnMaxLifetime(time.Hour)

	return db
}

type TableNamePlugin struct {
	tableName string
}

func (p *TableNamePlugin) Name() string {
	return "table_name_plugin"
}

func (p *TableNamePlugin) Initialize(db *gorm.DB) error {
	db.Callback().Create().Before("gorm:create").Register("change_table_name", p.changeTableName)
	db.Callback().Query().Before("gorm:query").Register("change_table_name", p.changeTableName)
	db.Callback().Update().Before("gorm:update").Register("change_table_name", p.changeTableName)
	db.Callback().Delete().Before("gorm:delete").Register("change_table_name", p.changeTableName)
	return nil
}

func (p *TableNamePlugin) changeTableName(db *gorm.DB) {
	if db.Statement.Schema != nil && p.tableName != "" {
		db.Statement.Table = p.tableName
	}
}

// 使用插件
func RunPlugin() {
	db := initDb()

	// 注册插件
	db.Use(&TableNamePlugin{tableName: "custom_users"})

	// 现在所有操作都会使用custom_users表
	var user model.User
	db.First(&user) // 查询custom_users表
}
